package com.nan.hrm.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQConfig {
    public static final String EXCHANGE_NAME_TOPIC="exchange_name_topic";
    public static final String QUEUE_NAME_EMAIL="queue_name_email";
    public static final String QUEUE_NAME_SMS="queue_name_sms";
    public static final String QUEUE_NAME_SYSTEM="queue_name_system";

    // 创建topic交换机
    @Bean
    public Exchange createExchange(){
        return ExchangeBuilder.topicExchange(EXCHANGE_NAME_TOPIC).build();
    }

    //创建队列
    @Bean(QUEUE_NAME_EMAIL)
    public Queue emailQueue(){
        return new Queue(QUEUE_NAME_EMAIL);
    }
    //创建队列
    @Bean(QUEUE_NAME_SMS)
    public Queue smsQueue(){
        return new Queue(QUEUE_NAME_SMS);
    }
    //创建队列
    @Bean(QUEUE_NAME_SYSTEM)
    public Queue systemQueue(){
        return new Queue(QUEUE_NAME_SYSTEM);
    }

    //绑定交换机
    @Bean
    public Binding emailBinding(){
        return BindingBuilder.bind(emailQueue()).to(createExchange()).with("#.email").noargs();
    }
    //绑定交换机
    @Bean
    public Binding smsBinding(){
        return BindingBuilder.bind(smsQueue()).to(createExchange()).with("#.sms").noargs();
    }
    //绑定交换机
    @Bean
    public Binding systemBinding(){
        return BindingBuilder.bind(systemQueue()).to(createExchange()).with("#.system").noargs();
    }

    //定义RabbitTemplate 指定 JSON转换器
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
        //1.把要发送的消息内容 ，交换机，rontkey等都保存下来到Mysql
        //2.后续可以用来重写发送消息，甚至可以使用一个定时任务不停的重试，可以甚至一个最大重试次数
        //设置消息回调
        rabbitTemplate.setMandatory(true);

        return rabbitTemplate;
    }
}
